import * as api from '../../api/api.js';
import db from '../../utils/db.js';
import { ASSETS } from '../../config.js';
const app = getApp()
const os = app.os;
let movableLoc = [0, 0];

Page({
  data: {
    assets: ASSETS,
    windowHeight: 0,
    topHeight: 0,
    movableX: 0,
    movableY: -150,
    currentPage: 1,
    pageTotal: 1,
    limit: 15,
    isEnd: false,
    isLoading: true,
    showHistory: false,
    showHistoryBox: true,
    historyData: null,
    refreshing: false,
    refreshEnabled: false,
    opacity: 1,
    dataList: [],
    showBackAdDialog: false,
    retainData: {
      data: false,
      currentAblum: false
    }
  },

  onReady: function () {
    let res = os.getMenuButtonBoundingClientRect();
    this.setData({
      topHeight: res.bottom || 100
    });

    app.sendAppLogs('app', 3); // 日志
  },

  onLoad: function () {
    os.setNavigationBarTitle({
      title: app.globalData.appName
    });

    this.getPlayletList();
  },

  onShow: function () {
    // 挽留广告
    if (app.globalData.showAdNum <= 0) {
      setTimeout(() => {
        this.showBackAdDialog();
      }, 1000);
    }

    // 观看历史
    // this.getHistoryList();
    this.getSeenHistoryData();
    app.delayAdDialog();
  },

  /**
   * 页面隐藏
   */
  onHide() {
    app.delayAdDialog(false);
  },

  /**
   * 显示挽留广告
   */
  showBackAdDialog: function () {
    const currentAblum = app.backAdData !== false ? app.backAdData?.currentAblum: db.getLastSeenHistory();
    app.echo('backAd', currentAblum);
    if (currentAblum !== false && app.globalData.appType === 1) {
      app.globalData.showAdNum++;
      this.setData({
        showBackAdDialog: true,
        retainData:{
          data: {
            unlock_num: currentAblum?.back_unlock_num || 1, 
            free_ad_btn: false, 
            title: '恭喜获得免费看剧权限', 
            cover_img: currentAblum?.cover_img
          },
          currentAblum: currentAblum,
        }
      });
    }
  },

  /**
   * 加载数据
   */
  onloadPageData: function (){
    let currentPage = this.data.currentPage + 1;
    if (currentPage <= this.data.pageTotal){
      this.setData({currentPage: currentPage});
      this.getPlayletList();
    }
  },

  /**
   * 获取短剧列表
   */
  getPlayletList: function () {
    const that = this;
    api.getPlayletList({
      page: this.data.currentPage,
      limit: this.data.limit,
    }).then(res => {
      let dataList = that.data.dataList;
      let isEnd = false;
      let isLoading = false;
      if (res.code == 200) {
        if(res.data.current_page == 1){
          dataList = [];
        }
        if(res.data.list.length > 0){
          dataList = dataList.concat(res.data.list);
        }
        if(res.data.current_page >= res.data.total_page && res.data.count > 0){
          isEnd = true;
        }
        if(res.data.current_page < res.data.total_page && res.data.count > 0){
          isLoading = true;
        }
        that.setData({
          dataList: dataList, 
          currentPage: parseInt(res.data.current_page), 
          pageTotal: res.data.total_page,
          isEnd: isEnd,
          refreshing: false,
          isLoading: isLoading
        });
      }else{
        that.setData({
          refreshing: false,
          isLoading: false
        });
        return app.Tips({title: res.msg});
      }
    }).catch(err => {
      that.setData({
        refreshing: false,
        isLoading: false
      });
    });
  },

  /**
   * 下拉刷新
   */
  onRefresh(e){
    const tabIndex = e.currentTarget.dataset.index;
    this.setData({
      refreshing: true,
      currentPage: 1
    });

    const that = this;
    setTimeout(() => {
      that.getPlayletList();
    }, 500);
  },

  /**
   * 获取观看历史数据
   */
  getHistoryList: function () {
    const that = this;
    api.getCollectList({
      limit: 1,
      type: 2
    },{showErr: false}).then(res => {
      if(res.code == 200 && res.data.list.length > 0){
        that.setData({
          historyData: res.data.list[0], 
        });
        if (that.data.showHistory || that.data.showHistoryBox) {
          setTimeout(() => {
            that.closeHistoryBox()
          }, 5000);
        }
      }
    });
  },

  getSeenHistoryData: function () {
    const _this = this;
    const { showHistory, showHistoryBox } = this.data;
    const data = db.getSeenLastData();
    if(data){
      this.setData({
        historyData: data, 
      });
      if (showHistory || showHistoryBox) {
        setTimeout(() => {
          _this.closeHistoryBox()
        }, 5000);
      }
    }
  },

  /**
   * 关闭查看历史
   */
  closeHistory: function () {
    this.setData({
      showHistory: false, 
      showHistoryBox: false
    });
  },

  /**
   * 关闭历史
   */
  closeHistoryBox: function () {
    this.setData({
      showHistory: true, 
      showHistoryBox: false
    });
  },

  /**
   * 移动可移动盒子
   */
  movableChange: function (e) {
    movableLoc[0] = e.detail.x;
    movableLoc[1] = e.detail.y;
    this.setData({movableX: movableLoc[0], movableY: movableLoc[1]});
  },

  /**
   * 按下可移动盒子
   */
  movableTouchstart: function () {
    this.setData({opacity: 0.5});
  },

  /**
   * 松开可移动盒子
   */
  movableTouchend: function () {
    const that = this;
    that.setData({opacity: 1});
    setTimeout(function(){
      that.setData({movableX: movableLoc[0] > 170 ? 390:0, movableY: movableLoc[1]});
    }, 100);
  },

  /**
   * 页面滑动
   */
  onScroll: function(e) {
    this.onSlideEvent(e);
    if (e.detail.scrollTop <= 1) {
      this.setData({refreshEnabled: true});
    } else {
      if (this.data.refreshEnabled !== false) {
        this.setData({refreshEnabled: false});
      }
    }
  },

  /**
   * 滑动事件
   */
  onSlideEvent: function(e) {
    if (this.scrollHeight === undefined) {
      this.scrollHeight = [0, 0];
    }
    
    this.scrollHeight[1] = parseInt(e.detail.scrollTop);

    if (this.slideTimeId) {
      clearTimeout(this.slideTimeId);
    }
    
    this.slideTimeId = setTimeout(() => {
      clearTimeout(this.slideTimeId);

      if(this.scrollHeight[0] !== this.scrollHeight[1]){
        app.sendAppLogs('app', 5, {
          method_mark: this.scrollHeight[0],
          method_mark_1: this.scrollHeight[1],
        });
        this.scrollHeight[0] = this.scrollHeight[1];
      }

    }, 300);
  },

  /**
   * 跳到搜索页
   */
  toSearchPage: function () {
    os.navigateTo({
      url: "/pages/search/search"
    });
  },

  /**
   * 跳到播放页
   */
  toVideoPage: function (e) {
    app.goPlayVideoPage(e.currentTarget.dataset.item.playlet_id);
  },

  /**
   * 广告挽留弹框-关闭
   */
  popClose: function () {
    app.backAdData = false;
    this.setData({
      showBackAdDialog: false,
      retainData: {
        data: false,
        currentAblum: false
      }
    });
  },

  /**
   * 广告挽留弹框-确定
   */
  onPopConfirm(e) {
    app.goPlayVideoPage(this.data.retainData.currentAblum.playlet_id);
    app.globalData.showAdNum = 3;
    db.clearLastSeenHistory();
    this.popClose();
  },

  /**
   * 广告挽留弹框-取消
   */
  onPopCancel(e) {
    this.popClose();

    if ((e.detail.type === 'closeAd' || app.globalData.isAdRogueVer) && app.globalData.showAdNum <= 2) {
      setTimeout(() => {
        if (app.globalData.showAdNum <= 2) {
          this.showBackAdDialog();
        }
      }, 1000);
    }
  },
})
